<template>
  <div>
    <el-upload
      class="upload-demo"
      :action="url"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
      :limit="1"
      accept=".pdf"
      :file-list="fileList"
    >
    
      <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
      <!-- <div slot="tip" class="el-upload__tip"></div> -->
    </el-upload>
  </div>
</template>

<script>
import Cookies from "js-cookie";
const MAX_FILESIZE = 200 * 1024 * 1024;
export default {
  props: [ "fileData" ],
  data() {
    return {
      fileList: [],
      url: "",
    };
  },
  mounted(){
    if(this.fileData)
      this.fileList = JSON.parse(JSON.stringify(this.fileData))
    this.$nextTick(() => {
      this.init();
    });
  },
  watch:{
    fileData(val){
      if(val)
      this.fileList = JSON.parse(JSON.stringify(val))
    }
  },
  methods: {
    init() {
      this.url = `${window.SITE_CONFIG['apiURL']}/cgjybzMessage/fileUpload?token=${Cookies.get('token')}`
    }, 
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isLtM = file.size < MAX_FILESIZE;
      if (!isLtM) {
        this.$message.error('文件大小超过200MB限制');
      }
      return isLtM;
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    // 删除文件
    handleRemove (file, fileList) {
      this.fileList = fileList;
      this.$emit('fileChange', this.getFiles())
    },
    handleSuccess(res, file){
      this.$emit('fileChange', this.getFiles())
    },
    getFiles(){
      return this.fileList;
    },
  }
};
</script>

<style scoped>
.upload-demo {
  display: inline-block;
  margin-right: 10px;
}
</style>
